<?php
error_reporting(0);
require_once('./includes/mysql.connect.php');
require_once('./includes/ldap.config.php');
$icm_hostname = 'http://'.$_SERVER["HTTP_HOST"].rtrim(dirname($_SERVER["PHP_SELF"]), "/");

function objectToArray($d) {
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
            $d = get_object_vars($d);
        }
 
        if (is_array($d)) {
            /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return array_map(__FUNCTION__, $d);
    }
    else {
        // Return array
        return $d;
    }
}
if ($_GET['action'] == 'getTinyurl') {
    //gets the data from a URL
    function get_tiny_url($url)  {  
            $ch = curl_init();  
            $timeout = 5;  
            curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.urlencode($url));  
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);  
            $data = curl_exec($ch);  
            curl_close($ch);  
            return $data;  
    }

    //test it out!
    $new_url = get_tiny_url($_GET['url']);

    //returns http://tinyurl.com/65gqpp
    echo $new_url;
}
if ($_GET['action'] == 'shorturl') {
    define('YOURLS_PRIVATE', false);
    require_once( dirname(__FILE__).'/includes/YOURLS-1.6/yourls-api.php' );
}
if ($_POST['action'] == 'layerLoaded') {
    if (stripos($_SERVER['HTTP_REFERER'],'map.geog.ucsb.edu') != false) {
        $mysqli->query("INSERT INTO `icm`.`analytics_layersloaded` (`layer`, `ip`) VALUES ('".$mysqli->real_escape_string($_REQUEST['layer'])."', '".$_SERVER['REMOTE_ADDR']."')");
    }
}
if ($_GET['action'] == 'listEnergyDataBuildings') {
        $query = "SELECT `bldgNumber` FROM  `energydata_bldg_eempointid_links` GROUP BY  `bldgNumber` ORDER BY  `bldgNumber`";
            if ($result = $mysqli->query($query)) {
                //printf("Select returned %d rows.\n", $result->num_rows);
                //$output['count'] = $result->num_rows;
                for ($i=0; $i < ($result->num_rows); $i++) {
                    //print_r($row);
                    $row = $result->fetch_array(MYSQLI_ASSOC);
                    if ($_GET['featuresAsArrays'] == true) {
                        $output[] = array((int)$row['bldgNumber']);
                    }
                    else {
                        $output[] = (int)$row['bldgNumber'];
                    }
                }
            }
            else {
                print(mysqli_error($mysqli));   
            }
            print (json_encode($output));
}
if ($_GET['action'] == 'getEnergyData') {
    if ($_GET['bldgNumber']) {
        //$searchText = explode(' ',$_GET['searchText']);

            //$query = "SELECT `bldg_number`,`eem_point_id`,`eem_point_name`,`result_units`, SUM(`value`) as values_sum, year(`period_end`) AS year, month(`period_end`) as month FROM `energydata_raw` WHERE `period_end` LIKE '%2012%' AND `bldg_number` = '".$_GET['bldgNumber']."' GROUP BY `bldg_number` ASC, year(`period_end`), month(`period_end`)";
            //$query = "SELECT `bldg_number`,`eem_point_id`,`eem_point_name`,`result_units`, SUM(`value`) as values_sum, year(`period_end`) AS year, month(`period_end`) as month FROM energydata_raw GROUP BY `bldg_number` ASC, year(`period_end`), month(`period_end`) LIMIT 0, 30";
            //
            //
            //MySQL Query WITH JOIN, sorted by Name, year & Month ASC.
            // SELECT `bldg_number`,`energydata_bldg_eempointid_links`.`eem_point_id`,`eem_point_name`,`result_units`, SUM(`value`) as values_sum, year(`period_end`) AS year, month(`period_end`) as month 
            //  FROM `energydata_raw`
            //  LEFT JOIN `energydata_bldg_eempointid_links` on `energydata_raw`.`eem_point_id` = `energydata_bldg_eempointid_links`.`eem_point_id`
            //  WHERE `energydata_bldg_eempointid_links`.`eem_point_id` != 'NULL'
            //  GROUP BY `bldg_number` ASC, year(`period_end`), month(`period_end`)
            //  ORDER BY `energydata_raw`.`eem_point_name` ASC, `year` ASC, `month` ASC
            //
            //
            //
            //
        if ($_GET['interval'] == 'daily') {
            $interval = $_GET['interval'];
            $query = "SELECT `bldg_number`,`energydata_bldg_eempointid_links`.`eem_point_id`,`eem_point_name`,`result_units`, SUM(`value`) as values_sum, year(`period_end`) AS year, month(`period_end`) as month, day(`period_end`) as day
              FROM `energydata_raw`
              LEFT JOIN `energydata_bldg_eempointid_links` on `energydata_raw`.`eem_point_id` = `energydata_bldg_eempointid_links`.`eem_point_id`
              WHERE `energydata_bldg_eempointid_links`.`eem_point_id` != 'NULL' AND `energydata_bldg_eempointid_links`.`bldgNumber` LIKE '%".$_GET['bldgNumber']."%' AND `period_end` <  '".date("Y")."-".date("m")."-01 00:00:00'
              GROUP BY `bldg_number` ASC, year(`period_end`), month(`period_end`), day(`period_end`)
              ORDER BY `energydata_raw`.`eem_point_name` ASC, `year` ASC, `month` ASC, `day` ASC";
        }
        elseif ($_GET['interval'] == 'hourly') {
            $interval = $_GET['interval'];
            $query = "SELECT `bldg_number`,`energydata_bldg_eempointid_links`.`eem_point_id`,`eem_point_name`,`result_units`, SUM(`value`) as values_sum, year(`period_end`) AS year, month(`period_end`) as month, day(`period_end`) as day, hour(`period_end`) as hour
              FROM `energydata_raw`
              LEFT JOIN `energydata_bldg_eempointid_links` on `energydata_raw`.`eem_point_id` = `energydata_bldg_eempointid_links`.`eem_point_id`
              WHERE `energydata_bldg_eempointid_links`.`eem_point_id` != 'NULL' AND `energydata_bldg_eempointid_links`.`bldgNumber` LIKE '%".$_GET['bldgNumber']."%' AND `period_end` <  '".date("Y")."-".date("m")."-01 00:00:00'
              GROUP BY `bldg_number` ASC, year(`period_end`), month(`period_end`), day(`period_end`), hour(`period_end`)
              ORDER BY `energydata_raw`.`eem_point_name` ASC, `year` ASC, `month` ASC, `day` ASC, `hour` ASC";
        }
        else { // Default is monthly aggregation
            $interval = 'monthly';
            $query = "SELECT `bldg_number`,`energydata_bldg_eempointid_links`.`eem_point_id`,`eem_point_name`,`result_units`, SUM(`value`) as values_sum, year(`period_end`) AS year, month(`period_end`) as month 
              FROM `energydata_raw`
              LEFT JOIN `energydata_bldg_eempointid_links` on `energydata_raw`.`eem_point_id` = `energydata_bldg_eempointid_links`.`eem_point_id`
              WHERE `energydata_bldg_eempointid_links`.`eem_point_id` != 'NULL' AND `energydata_bldg_eempointid_links`.`bldgNumber` LIKE '%".$_GET['bldgNumber']."%' AND `period_end` <  '".date("Y")."-".date("m")."-01 00:00:00'
              GROUP BY `bldg_number` ASC, year(`period_end`), month(`period_end`)
              ORDER BY `energydata_raw`.`eem_point_name` ASC, `year` ASC, `month` ASC";
        }
            
                //$output['query'] = $query;
            if ($result = $mysqli->query($query)) {
            //printf("Select returned %d rows.\n", $result->num_rows);
            $output['interval'] = $interval;
            $output['count'] = $result->num_rows;
                for ($i=0; $i < ($result->num_rows); $i++) {
                    //print_r($row);
                    $row = $result->fetch_array(MYSQLI_ASSOC);
                    $output['results'][$i] = $row;
                }
            }
            else {
            print(mysqli_error($mysqli));
            }
            if ($_GET['returnOnlyData'] == true) {
                $data = array();
                foreach ($output['results'] as $result) {
                    //print_r($result);
                    if ($output['interval'] == 'monthly') {
                        $data[] = array( (strtotime($result['year'].'-'.$result['month']) *1000) ,(int)$result['values_sum']);
                    }
                }
                if (count($data) > 0) {
                    print(json_encode($data));
                }

            }
            else {
                print(json_encode($output));
            }
       } 
}
if ($_GET['action'] == 'peopleSearch') {
    $q = str_replace(' ', '*',$_GET['searchText']);
            // basic sequence with LDAP is connect, bind, search, interpret search
            // result, close connection
            //echo "<pre>";
            //echo "Connecting ...";
            $ds=ldap_connect("ldaps://ldap.ucsb.edu:636");  // must be a valid LDAP server!
            //echo "connect result is " . $ds . "<br />";
            
            if ($ds) { 
                //echo "Binding ..."; 
                $r=ldap_bind($ds,$ldap_dn,$ldap_password);

                //echo "Bind result is " . $r . "<br />";
            
                //echo "Searching for (!street=) ...";
                // Search surname entry
                $sr=ldap_search($ds, "o=ucsb", "(&(street=*) (cn=*".$q."*))");
                //echo "Search result is " . $sr . "<br />";
            
                //echo "Number of entries returned is " . ldap_count_entries($ds, $sr) . "<br />";
                $persons['count'] = ldap_count_entries($ds, $sr);
            
                //echo "Getting entries ...<p>";
                $info = ldap_get_entries($ds, $sr);
                //echo "Data for " . $info["count"] . " items returned:<p>";
            
                for ($i=0; $i<$info["count"]; $i++) {
                    $persons['results'][$i]['name'] = $info[$i]["cn"][0];
                    $persons['results'][$i]['ucsbaffiliation'] = $info[$i]["ucsbaffiliation"];
                    $persons['results'][$i]['location'] = $info[$i]["street"][0];
                    $url = 'http://localhost/api.php?action=getRoomGeometry&searchText='.urlencode($persons['results'][$i]['location']);
		    $roomJSON = file_get_contents($url);
					
                    //print($url);
                    //print($roomJSON);
		    $roomsJSON = json_decode($roomJSON);
		    $roomsJSON = objectToArray($roomsJSON);
                    //print('<br />');
                    //print_r($roomsJSON);
                    //print_r($roomsJSON['results'][0]);
                    $persons['results'][$i]['geometry'] = $roomsJSON['results'][0]['geometry'];
                    //print($roomsJSON->results[0]['label']);
                    //print_r($roomsJSON['results'][0]);
                    //print_r($info[$i]);
                    //echo "<hr />";
                }
                print json_encode($persons);
                //echo "Closing connection";
                ldap_close($ds);
            
            } else {
                echo "Unable to connect to LDAP server";
            }
}
if ($_GET['action'] == 'getRoomGeometry') {
		$output['count'] = 0;	
		$qURL = 'http://localhost:8983/solr/db/select?fq=category%3Arooms&start=0&rows=1&wt=json&indent=true&q='.urlencode($_GET['searchText']);
		//print($qURL);
    	$solr_results = file_get_contents($qURL);
		$solr_results = objectToArray(json_decode($solr_results));
		//print_r($solr_results);
		foreach($solr_results['response']['docs'] as $result) {
			$output['results'][$output['count']]['label'] = $result['label'];
			$output['results'][$output['count']]['geometry'] = $result['geometry'];
			$output['count']++;
		}
		print(json_encode($output));
}
// REPLACED BY NEW getRoomGeometry FUNCTION (8/15/2013)
// -Bryan Karaffa
if ($_GET['action'] == 'getRoomGeometry-v0') {
	        $searchText = explode(' ',$_GET['searchText']);
	        $query = "SELECT `label`,`geometry`, MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'rooms' AND MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) LIMIT 0,1";
	        //$query = "SELECT `label`,`geometry`, MATCH (`tags`) AGAINST ('Ellison 1709' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'rooms' AND MATCH (`tags`) AGAINST ('%Ellison 1709%' IN NATURAL LANGUAGE MODE) LIMIT 0,1";
			//$output['query'] = $query;
	        if ($result = $mysqli->query($query)) {
	            //printf("Select returned %d rows.\n", $result->num_rows);
	            $output['count'] = $result->num_rows;
	            for ($i=0; $i < ($result->num_rows); $i++) {
	                print_r($row);
	                $row = $result->fetch_array(MYSQLI_ASSOC);
					$output['results'][$i] = $row;
	            }
	        }
	        else {
	            print(mysqli_error($mysqli));
	        }
			print(json_encode($output));
	         /* free result set */
	        $result->close();    
	        
		
}
if ($_GET['action'] == 'searchboxSearch') {
	if ($_SERVER['SERVER_NAME'] == 'map.geog.ucsb.edu') {
        $mysqli->query("INSERT INTO `icm`.`analytics_searched_values` (`search_term`, `user_ip`) VALUES ('".$mysqli->real_escape_string($_GET['searchText'])."', '".$_SERVER['REMOTE_ADDR']."')");
    }
    $total_results = 0;
	$limit_results = 10;
    $CategoryArray = array(
    		"rooms" => "Rooms",
    		"class" => "Classes",
    		"section" => "Sections",
    		"buildings" => "Buildings",
    		"foodestablishments" => "Food Establishments",
    		"campusservice" => "Campus Services",
    		"parking" => "Parking Areas",
    		"recreationarea" => "Recreation Areas"
			);
			//echo 'Starting v2';
			$qURL = 'http://localhost:8983/solr/db/select?wt=json&indent=true&group=true&group.field=category&group.limit='.$limit_results.'&group.format=grouped&&spellcheck=true&q='.urlencode($_GET['searchText']);
			//print($qURL);
    	$solr_results = file_get_contents($qURL);
		//print_r($solr_results); 
		$solr_results = objectToArray(json_decode($solr_results));
		foreach($solr_results['grouped']['category']['groups'] as $cat) {
			//print($cat['groupValue']."\n");
			//print_r($cat['doclist']['docs']);
			//$output['results'][$cat['groupValue']]['count'] = '1';
			$i = 0;
			foreach ($cat['doclist']['docs'] as $doc) {
				$output['results'][$cat['groupValue']][$i++] = $doc;
			}
			$output['results'][$cat['groupValue']]['count'] = $i;
			$output['total_count'] = $output['total_count'] + $i;
			//$output['results'][$cat['groupValue']] = objectToArray($cat['doclist']['docs']);
			//echo "=============================================================================\n\n\n\n\n\n\n\n\n\n";
		}
		
		
		$people_results = file_get_contents('http://localhost/api.php?action=peopleSearch&searchText='.urlencode($_GET['searchText']));
        $people_results = objectToArray(json_decode($people_results));
        //print_r($people_results);
        if ($people_results['count'] > 0) {
            if($people_results['count'] < $limit_results) { $limit_results = $people_results['count']; }
            for ($i=0; $i < $limit_results; $i++) {
            	//print_r($output['results']['people'][$i]);
                $output['results']['people']['count'] = $i+1;
                //$output['results']['people'][$i] = $people_results['results'][$i];
                $output['results']['people'][$i]['label'] = $people_results['results'][$i]['name'];
                $output['results']['people'][$i]['geometry'] = $people_results['results'][$i]['geometry'];
                $output['results']['people'][$i]['location'] = $people_results['results'][$i]['location'];
                //print('<pre>');
                //print_r($output['results']['people']);
                //print('<br />');
                $output['total_count']++;
    
                //$output['results']['people'][$i] = $people_results->results[$i];
            }
       }
		else {
			$output['extendedPeopleSearch'] = true;
			$mirror_array = explode(' ', $_GET['searchText']);
			$lastword = $mirror_array[(count($mirror_array) -1)]; 
			$people_results = file_get_contents('http://localhost/api.php?action=peopleSearch&searchText='.urlencode($lastword));
        	$people_results = objectToArray(json_decode($people_results));
	        if ($people_results['count'] > 0) {
	            if($people_results['count'] < $limit_results) { $limit_results = $people_results['count']; }
	            for ($i=0; $i < $limit_results; $i++) {
	                $output['results']['people']['count'] = $i+1;
	                $output['results']['people'][$i]['label'] = $people_results['results'][$i]['name'];
	                $output['results']['people'][$i]['geometry'] = $people_results['results'][$i]['geometry'];
	                $output['results']['people'][$i]['location'] = $people_results['results'][$i]['location'];
	                $output['total_count']++;
				} 			
			}
		}
		
		
		//print('=================================');
		//print_r($output);
		$output = array_filter($output);
		print json_encode($output); //JSON_PRETTY_PRINT only works on php version 5.4+ which is not installed on the web servers.
//		print_r($solr_results);    		
}
// REPLACED BY NEW SEARCHBOXSEARCH FUNCTION (8/15/2013)
// -Bryan Karaffa
if ($_GET['action'] == 'searchboxSearch-v0') {
    if ($_SERVER['SERVER_NAME'] == 'map.geog.ucsb.edu') {
        $mysqli->query("INSERT INTO `icm`.`analytics_searched_values` (`search_term`, `user_ip`) VALUES ('".$mysqli->real_escape_string($_GET['searchText'])."', '".$_SERVER['REMOTE_ADDR']."')");
    }
    if ($_GET['expandedSearch'] == 1) {      
        
    }
    else {
        $total_results = 0;
        $output['total_count'] = $total_results;    
        $categories = array('rooms','building','class','department','campusservice','parking');
        $limit_results = 10;
        //$searchText = explode(' ',$_GET['searchText']);
        $query['rooms'] = "SELECT `label`,`geometry`,`location`, MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'rooms' AND MATCH (`tags`) AGAINST ('%".$_GET['searchText']."%' IN NATURAL LANGUAGE MODE) LIMIT 0,".$limit_results;
        $query['building'] = "SELECT `label`,`geometry`,`location`, MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'building' AND MATCH (`tags`) AGAINST ('%".$_GET['searchText']."%' IN NATURAL LANGUAGE MODE ) LIMIT 0,".$limit_results;
        $query['class'] = "SELECT `label`,`geometry`,`location`, MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'class' AND MATCH (`tags`) AGAINST ('%".$_GET['searchText']."%' IN NATURAL LANGUAGE MODE) LIMIT 0,".$limit_results;
        $query['department'] = "SELECT `label`,`geometry`,`location`, MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'department' AND MATCH (`tags`) AGAINST ('%".$_GET['searchText']."%' IN NATURAL LANGUAGE MODE) LIMIT 0,".$limit_results;
        $query['campusservice'] = "SELECT `label`,`geometry`,`location`, MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'campusservice' AND MATCH (`tags`) AGAINST ('%".$_GET['searchText']."%' IN NATURAL LANGUAGE MODE) LIMIT 0,".$limit_results;
        $query['parking'] = "SELECT `label`,`geometry`,`location`, MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'parking' AND MATCH (`tags`) AGAINST ('%".$_GET['searchText']."%' IN NATURAL LANGUAGE MODE) LIMIT 0,".$limit_results;
        
        //$query = "SELECT `label`,`geometry`, MATCH (`tags`) AGAINST ('Ellison 1709' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE `category` LIKE 'rooms' AND MATCH (`tags`) AGAINST ('%Ellison 1709%' IN NATURAL LANGUAGE MODE) LIMIT 0,1";
        //$output['query'] = $query;
        foreach ($categories as $category) {
            if ($result = $mysqli->query($query[$category])) {
                //printf("Select returned %d rows.\n", $result->num_rows);
                if ($result->num_rows > 0) {
                    $output['results'][$category]['count'] = $result->num_rows;
                    for ($i=0; $i < ($result->num_rows); $i++) {
                        $row = $result->fetch_array(MYSQLI_ASSOC);
                        //print_r($row);
                        $output['results'][$category][$i] = $row;
                        $total_results++;
                    }
                }
            }
            else {
                print(mysqli_error($mysqli));
            }
            //$output['results'][$category] = $output;
            //$output.=$output;
            //print(json_encode($output));
             /* free result set */
            $result->close();
        }
        
        $people_results = file_get_contents('http://localhost/api.php?action=peopleSearch&searchText='.urlencode($_GET['searchText']));
        $people_results = objectToArray(json_decode($people_results));
        //print_r($people_results);
        if ($people_results['count'] > 0) {
            if($people_results['count'] < $limit_results) { $limit_results = $people_results['count']; }
            for ($i=0; $i < $limit_results; $i++) {
                $output['results']['people']['count'] = $i+1;
                //$output['results']['people'][$i] = $people_results['results'][$i];
                $output['results']['people'][$i]['label'] = $people_results['results'][$i]['name'];
                $output['results']['people'][$i]['geometry'] = $people_results['results'][$i]['geometry'];
                $output['results']['people'][$i]['location'] = $people_results['results'][$i]['location'];
                //print('<pre>');
                //print_r($output['results']['people']);
                //print('<br />');
                $total_results++;
    
                //$output['results']['people'][$i] = $people_results->results[$i];
            }
        }
        $output = array_filter($output);
        $output['total_count'] = $total_results;
            print json_encode($output);    
    }

}
if ($_GET['action'] == 'searchMap') {
	if(isset($_GET['searchText'])) {
	        //            
	        // Method 1: LIKE %...%
	        //    
	        //$searchText = explode(' ',$_POST['searchText']);
	        //$WHERE = '';
	        //foreach($searchText as $string) {
	        //    $WHERE .= "LOWER(`tags`) LIKE  LOWER('%".$string."%') OR ";
	        //}
	        //$WHERE = substr($WHERE,0,-3);
	        //$query = "SELECT * FROM  `searchablefeatures` WHERE ".$WHERE;
	        
	        //
	        // Method 2: FULLTEXT Search
	        //
	        $query = "SELECT *, MATCH (`tags`) AGAINST ('".$_GET['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE MATCH (`tags`) AGAINST ('%".$_GET['searchText']."%' IN NATURAL LANGUAGE MODE)";
	        
			//$output['query'] = $query;
	        if ($result = $mysqli->query($query)) {
	            //printf("Select returned %d rows.\n", $result->num_rows);
	            $output['count'] = $result->num_rows;
	            for ($i=0; $i < ($result->num_rows); $i++) {
	                $row = $result->fetch_array(MYSQLI_ASSOC);
					$output['results'][$i] = $row;
	            }
	        }
	        else {
	            print(mysqli_error($mysqli));
	        }
			print(json_encode($output));
	         /* free result set */
	        $result->close();        
    }
}
if ( !isset($_GET['action']) && !isset($_POST['action']) ) {
	$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	print ("
<pre>University of California, Santa Barbara Interactive Campus Map Data API
Presented by the UCSB Geography Department

README:
This API is used directly by the ICM and powers the Energy Data and Search Map modules.  
Those who are interested are encouraged to use the data that we provide for nonprofit or educational purposes.
All requests are made by settings parameters in the url and results are returned in JSON format.

All parameters and settings are CASE SENSITIVE.. This means searchmap is not the same as searchMap or SEARCHMAP.  
If you are getting no results, make sure your parameters and settings are correct.

Possible functions: searchMap | peopleSearch | listEnergyDataBuildings | getEnergyData

Documentation:

SM   -- Search Map (api.php?action=searchMap) --
SM   Queries ICM Database and returns a unique feature-id, authoritative name (label), tags, feature type (category),
SM    and spatial geometry (location) for use in the ICM.
SM   
SM   Searchable features: (see below for examples)
SM		289 	Buildings
SM		3452	Classes (including sections) for the current quarter
SM		52 	Departments by name
SM		8866	Rooms by Building / room combination
SM		(Updated: 1/30/2013)
SM      
SM   Required Parameters: action=searchMap | searchText=__Search This__
SM     
SM   Output: JSON Array
SM     
SM   Examples: Building:      $pageURL?action=searchMap&searchText=Ellison Hall
SM             Class:         $pageURL?action=searchMap&searchText=GEOG 176A
SM                            $pageURL?action=searchMap&searchText=Geography of Surfing
SM             Department:    $pageURL?action=searchMap&searchText=Geography
SM             Room:          $pageURL?action=searchMap&searchText=Ellison 1710
SM                            $pageURL?action=searchMap&searchText=ELLSN 1710

PS   -- People Search (api.php?action=peopleSearch) --
PS   Queries the UCSB Directory and returns the name, classification, and location for that person. 
PS   ***********************************************************************************
PS   ****** Please note, this API is not meant to replace the UCSB People Finder. ****** 
PS   ** This function is only in place as a requirement for other functions to work. ***
PS   ***********************************************************************************   
PS     
PS   Required Parameters: action=peopleSearch | q=__Find This Name__
PS     
PS   Output: JSON Array
PS     
PS   Examples: $pageURL?action=peopleSearch&q=Bryan Karaffa
PS             $pageURL?action=peopleSearch&q=John Doe

LB   -- List Buildings With Energy Data (api.php?action=listEnergyDataBuildings) --
LB   Queries the ICM Energy Data Database and returns the buildings that have energy data.
LB    
LB     
LB    Required Parameters: action=listEnergyDataBuildings
LB     
LB    Output: JSON Array
LB     
LB    Example: $pageURL?action=listEnergyDataBuildings

GD    -- Get Energy Data (api.php?action=getEnergyData) --
GD    Returns the energy usage for a specified building.  Default aggregating interval is monthly.
GD
GD    Required Parameters: action=getEnergyData | bldgNumber=__#BuildingNumber#__ | 
GD         
GD    Optional Parameters: interval=hourly|daily|monthly
GD
GD    Output: JSON Array
GD
GD    Examples: $pageURL?action=getEnergyData&bldgNumber=563
GD              $pageURL?action=getEnergyData&bldgNumber=563&interval=daily
GD              $pageURL?action=getEnergyData&bldgNumber=563&interval=hourly
GD              $pageURL?action=getEnergyData&bldgNumber=563&interval=monthly
");
}
?>